#include "expcatview.h"
#include "ui_expcatview.h"
#include<QtSql/QSqlQuery>
#include<QDebug>
#include<QDesktopWidget>
//This show expense records either by category or by account
ExpCatView::ExpCatView(int id1,QString name1,QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ExpCatView)
{
    ui->setupUi(this);
    id=id1;
    name=name1;
    QString query;
    //ui->label_msg->setVisible(false);
    QRect innersize=QApplication::desktop()->availableGeometry(this);
    //ui->listWidget->setGeometry(0,50,(innersize.width()),(innersize.height()));
    ui->scrollArea->setGeometry(0,0,(innersize.width()),(innersize.height()));
    ui->listWidget->setEditFocus(true);
    QAction* backAction = new QAction( tr("Back"), this );
     backAction->setSoftKeyRole( QAction::NegativeSoftKey );
     connect(backAction, SIGNAL(triggered()), this, SLOT(back()));
     addAction( backAction );
     int fontSize=10;
     ui->label->setFont(QFont( "lucida", fontSize, QFont::Normal, FALSE ));
     if(id==1)
     {
         ui->label->setText(tr("Expenses by category"));
         query="select exp_id,exp_amt,exp_date from expense_table where cat_name='%1'";
     }
     else
     {
         ui->label->setText(tr("Expenses by account"));
         query="select exp_id,exp_amt,exp_date from account_table INNER JOIN expense_table ON account_table.account_id=expense_table.acc_id and name='%1'";
     }
     int count=0;
     if(db.db_connect())
     {
         QSqlQuery q;
         QString date;
         if(q.exec(query.arg(name)))
         {
             while(q.next())
             {
                 date=q.value(2).toDate().toString();
                 item1=new QListWidgetItem(QString("%1 : %2").arg(q.value(1).toDouble()).arg(date),ui->listWidget,QListWidgetItem::UserType);
                 item1->setFont(QFont( "lucida", fontSize, QFont::Normal, FALSE ));
                 item1->setToolTip(QString("%1").arg(q.value(0).toString()));
                 count++;
             }
             if(count==0)
             {
                // ui->label_msg->setVisible(true);
                 ui->listWidget->hide();
                // ui->label->setVisible(false);
                 ui->label->setText(tr("No expense record found"));
             }
         }
         db.db_close();
     }


}

ExpCatView::~ExpCatView()
{
    delete ui;
}

void ExpCatView::on_listWidget_itemActivated(QListWidgetItem* item)
{
    if(id==1)
    (new ExpDetails(item->toolTip().toInt(),5))->show();
    else
     (new ExpDetails(item->toolTip().toInt(),6))->show();
}
void ExpCatView::back()
{
    (new ExpByCat(id))->show();
}
